<?php

namespace App\Module\Sub;

use App\depository\ManageCMDDep;
use App\depository\TeamDictDep;
use App\Module\BaseModule;
use GuzzleHttp\Client;

class SubCmdModule extends BaseModule
{
    public function push($request){

        $param = $request->input();
        $teamId = $request->headers->get('TeamId');

        $dictDep = new TeamDictDep();
        $resDict = $dictDep->getByTeamId($teamId);

        $content = $param['content'];
        $rcon = $resDict->first(function ($item) {
            return $item->label == 'RCON地址';
        });

        if (!$rcon) {
            return self::response([], '请联系管理员添加RCON地址', 200);
        }

        $client = new Client();
        $url = $rcon->value . "{$content}";
        $response = $client->get($url);

        $body = $response->getBody();
        $bodyStr = (string)$body;
        if (!$bodyStr) {
            return self::response([], '连接失败', 200);
        }

        return self::response([], $bodyStr);

    }
    public function list($request){

        $param = $request->input();
        $teamId = $request->headers->get('TeamId');

        $param['team_id'] = $teamId;
        $param['current_page'] = isset($param['current_page']) ? $param['current_page'] : 1;
        $param['per_page'] = isset($param['per_page']) ? $param['per_page'] : 50;

        $dep = new ManageCMDDep();
        $resList = $dep->list($param);
        $list = $resList->getCollection()->toBase();
        $data['list'] = $list->map(function ($item) {
            return [
                'id' => $item->id,
                'ids' => $item->id,
                'time' => $item->time,
                'ip' => $item->ip,
                'content' => $item->content,
                'created_at' => $item->created_at->toDateTimeString()
            ];
        });
        $data['page'] = [
            'per_page' => $param['per_page'],
            'current_page' => $param['current_page'],
            'total_page' => $resList->lastPage(),
            'total' => $resList->total(),
        ];
        return self::response($data);

    }
}

